package com.rizzo.analytics.domain.quota;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.rizzo.infrastructure.web.validator.Save;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

import javax.validation.Valid;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.List;

public class Quotas implements Serializable {

	private static final long serialVersionUID = 2L;

	@Valid
	@Size(min = 1, message = "quotas.empty", groups = {Save.class})
	private List<Quota> quotas;

	public Quotas() {
	}

	public Quotas(List<Quota> quotas) {
		this.quotas = quotas;
	}

	public List<Quota> getQuotas() {
		if (quotas == null) {
			quotas = Lists.newArrayList();
		}
		return quotas;
	}

	public void setQuotas(List<Quota> quotas) {
		this.quotas = quotas;
	}

	public Quota getQuota(final String method) {
		Predicate<Quota> isQuota = new Predicate<Quota>() {

			@Override
			public boolean apply(Quota quota) {
				return quota.getMethod().equals(method);
			}

		};
		Iterable<Quota> filteredQuota = Iterables.filter(getQuotas(), isQuota);
		return Iterables.getFirst(filteredQuota, null);
	}

	public void merge(Quotas update) {
		for (Quota quota : update.getQuotas()) {
			Quota current = getQuota(quota.getMethod());
			current.setHits(quota.getHits());
		}
	}

	@Override
	public boolean equals(Object other) {
		return EqualsBuilder.reflectionEquals(other, this);
	}

	@Override
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}

	@Override
	public String toString() {
		return new ToStringBuilder(this).
				append("quotas", quotas).
				toString();
	}

}
